package service

import (
	"dataaysn/internal/model"
	"dataaysn/internal/repository"
	"fmt"
	"strconv"

	"github.com/gin-gonic/gin"
)

type HospitalService struct {
	repo repository.HospitalRepository
}

func NewHospitalService(repo repository.HospitalRepository) *HospitalService {
	return &HospitalService{repo: repo}
}

func (s *HospitalService) CreateHospital(c *gin.Context) {
	var hospital model.Hospital
	if err := c.ShouldBindJSON(&hospital); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	resp, err := s.repo.CreateHospital(&hospital)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, resp.Data)
}

func (s *HospitalService) GetHospital(c *gin.Context) {
	id := c.Param("id")
	resp, err := s.repo.GetHospital(id)
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, resp.Data)
}

func (s *HospitalService) UpdateHospital(c *gin.Context) {
	id := c.Param("id")
	var hospital model.Hospital
	if err := c.ShouldBindJSON(&hospital); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	uintID, err := strconv.ParseUint(id, 10, 32)
	if err != nil {
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	hospital.ID = uint(uintID)
	resp, err := s.repo.UpdateHospital(&hospital)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, resp.Data)
}

func (s *HospitalService) DeleteHospital(c *gin.Context) {
	id := c.Param("id")
	resp, err := s.repo.DeleteHospital(id)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, resp.Data)
}

func (s *HospitalService) ListHospitals(c *gin.Context) {
	// 支持通过 hospitalCode（医院编码）、hospitalName（医院名称）作为查询参数
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	var hospital model.Hospital
	// 绑定 hospitalCode、hospitalName 查询参数到 hospital 结构体
	hospital.HospitalCode = c.DefaultQuery("hospitalCode", "")
	hospital.HospitalName = c.DefaultQuery("hospitalName", "")
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}
	if err := c.ShouldBindQuery(&hospital); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	resp, err := s.repo.ListHospitals(&hospital, page, pageSize)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	// 打印所有医院编码到终端
	if hospitals, ok := resp.Data.([]model.Hospital); ok {
		for _, h := range hospitals {
			fmt.Println("医院编码:", h.HospitalCode)
		}
	}
	c.JSON(200, resp)
}
